import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.edu.zs.education.entity;"
typeMapping = [
        (~/(?i)tinyint|bool|bit/)                : "Boolean",
        (~/(?i)int|smallint|mediumint/)          : "Integer",
        (~/(?i)bigint/)                          : "Long",
        (~/(?i)float|double|decimal|real/)       : "BigDecimal",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?i)datetime|timestamp|date|time/)    : "LocalDateTime",
        (~/(?i)/)                                : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true) + "Entity"
    def fields = calcFields(table)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, table, className, fields) }
}

def generate(out, table, className, fields) {
    // 获取所有类型
    Set types = new HashSet()
    fields.each() {
        types.add(it.type)
    }

    out.println "package $packageName"
    out.println "import javax.persistence.*;"
    out.println "import org.hibernate.annotations.DynamicInsert;"
    out.println ""
    if (types.contains("InputStream")){
        out.println "import java.io.InputStream;"
    }
    if (types.contains("BigDecimal")) {
        out.println "import java.math.BigDecimal;"
    }
    if (types.contains("LocalDateTime")) {
        out.println "import java.time.LocalDateTime;"
    }
//    out.println "import java.io.Serializable;"

    out.println ""
    out.println "/**"
    out.println " * @author Madison"
    out.println " * @date ${DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())}"
    out.println " */"
    out.println "@Entity"
    out.println "@DynamicInsert"
    out.println "@Table(name = \"${table.getName()}\")"
    out.println "public class ${className} {"
//    out.println genSerialID()
//    out.println ""
    fields.each() {
        // 输出注释
        if (isNotEmpty(it.comment)) {
            out.println "\t/**"
            out.println "\t * ${it.comment.toString()}"
            out.println "\t */"
        }
        if (it.name == "id") out.println "\t@Id"
        if (it.name == "id") out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "\t@Column(name = \"${it.column}\")"
        out.println "\tprivate ${it.type} ${it.name};"
    }
    fields.each() {
        out.println ""
        out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
        out.println "\t\treturn ${it.name};"
        out.println "\t}"
        out.println ""
        out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "\t\tthis.${it.name} = ${it.name};"
        out.println "\t}"
        out.println ""
    }
//    out.println "\t@Override\n" +
//            "    public boolean equals(Object o) {\n" +
//            "        if (this == o) return true;\n" +
//            "        if (o == null || getClass() != o.getClass()) return false;\n" +
//            "        ChatUsersEntity that = (ChatUsersEntity) o;\n" +
//            "        return id == that.id &&\n" +
//            "                admin == that.admin &&\n" +
//            "                Objects.equals(openId, that.openId) &&\n" +
//            "                Objects.equals(unionid, that.unionid) &&\n" +
//            "                Objects.equals(name, that.name) &&\n" +
//            "                Objects.equals(gender, that.gender) &&\n" +
//            "                Objects.equals(createTime, that.createTime) &&\n" +
//            "                Objects.equals(updateTime, that.updateTime);\n" +
//            "    }\n" +
//            "\n" +
//            "    @Override\n" +
//            "    public int hashCode() {\n" +
//            "        return Objects.hash(id, openId, unionid, name, gender, admin, createTime, updateTime);\n" +
//            "    }"
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           comment: col.getComment(),
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           column: col.getName(),//字段注释
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def isNotEmpty(content) {
    return content != null && content.toString().trim().length() > 0
}
//生成序列化的serialVersionUID
static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}